package com.hugoo.core.db.pools;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Lovelock.Chan
 */
public final class EnvPool implements NiCP {

    private final static Log log = LogFactory.getLog(EnvPool.class);
    private Context ctx;
    private DataSource ds;
    private final String inst;

    public EnvPool(String inst) {
        this.inst = inst;
        init();
    }

    @Override
    public void init() {
        try {
            ctx = new InitialContext();
            ds = (DataSource) ctx.lookup(inst);
        } catch (NamingException ex) {
            log.error("无法取得数据源，从配置的环境中！", ex);
        }
    }

    @Override
    public Connection getConn() {
        if (ds != null) {
            try {
                return ds.getConnection();
            } catch (SQLException ex) {
                log.error("打开数据库连接失败！", ex);
            } catch (Exception ex) {
                log.error("无法取得数据源，从配置的环境中！", ex);
            }
        } else {
            log.error("连接池环境未初始化！");
        }
        return null;
    }
}
